package cn.jhc.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.jhc.bean.CartItem;
import cn.jhc.bean.Title;
import cn.jhc.bean.UserCookie;
import cn.jhc.bean.User;
import cn.jhc.dao.TitleDAO;

/**
 * Servlet implementation class ShowShoppingCartServlet
 */
@WebServlet("/user/addtocart.do")
public class AddToCart extends HttpServlet {
	private static final long serialVersionUID = 1L;

//	@Override
//	protected void doGet(HttpServletRequest request,
//			HttpServletResponse response) throws ServletException, IOException {
//		String isbn = (String) request.getSession().getAttribute("isbn");
//		String booknum = (String) request.getSession().getAttribute("count");
//		
//		direct(request, response, isbn, booknum);
//	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String booknum = request.getParameter("count");
		String isbn = request.getParameter("isbn");
		User user = (User)request.getSession().getAttribute("currentUser");	
		String username = user.getLoginname();
		String book = "";

		
		Cookie cookie = null;
		int num = 0;

		if (isbn != null && booknum != null) 
		{
			try {
				num = Integer.parseInt(booknum);
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//判断是否合理
			if(num <= 0)
			{
				response.sendRedirect("../list.htm");
				return;
			}
						
			book = "*" + isbn + "^" + num;
						
			Cookie[] cookies = request.getCookies();
			cookie = UserCookie.tranversal(cookies, username);
			
			//有cookie
			if (cookie != null) 
			{
				List<CartItem> cart = new ArrayList<>();
				cart = UserCookie.getCartItems(cookie);
				
				String value = "";
				boolean findSameBook = false;
				for (CartItem cartItem : cart) 
				{					
					// 判断是否为该书
					if (isbn.equals(cartItem.getIsbn()))
					{
//						System.out.println("yes");
						int a = cartItem.getNum() + num;
						value += "*" + cartItem.getIsbn() + "^"+ a;//修改该书数量
						findSameBook = true;
					}
					else 
					{
//						System.out.println("no");
						value += "*" + cartItem.getIsbn() + "^"+ cartItem.getNum();
					}
				}
//				System.out.println("value:" + value);
				if(findSameBook)
				{
					cookie.setValue(value);
				}
				else
				{					
					cookie.setValue(value + book);
				}
			}
			else 
			{			
//				System.out.println("book:" + book);
				cookie = new Cookie(username, book);
			}
			
			//设置cookie的有效时间为一小时			
			cookie.setMaxAge(60 * 60);
			
			
			//添加cookie
			response.addCookie(cookie);					
			
			//跳转到购物车			
			response.sendRedirect("../list.htm");

		}
	
	}

}
